from time import sleep
import os, sys
try:
    from googletrans import Translator
except:
    os.system('pip3 install googletrans==4.0.0-rc1')
    from googletrans import Translator

translator = Translator(service_urls=[r'translate.google.cn'], user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 Edge/87.0.664.66')

def main(a):

    s= open(a, encoding='UTF8', mode='r')
    s7= open('trans.'+os.path.basename(a),encoding='UTF8',mode='w')
    s2= s.readlines()

    s3= []
    while s2:
        s4= next((s2[:n] for n in range(len(s2), 0, -1) if len(' '.join(s2[:n]))<5000), s2[:1])
        s3.append('\n'.join(s4))
        s2= s2[len(s4):]

    s6= []
    for i in range(len(s3)):
        s8=s3[i]
        if len(s8)>5000:
            s6.append('%s:\t%s\t...\t%s' %(len(s8), s8[:20], s8[-20:]))
    if len(s6)>0:
        print("存在超过5000字的分段，将会在翻译时出错，请重新分段")
        print('\n'.join(s6))
        sys.exit()
    
    for i in s3:
        s5= None
        while s5 == None:
            try:
                s5= translator.translate(i,src='en',dest='zh-cn').text
                sleep(0.2)
            except: pass
        #s6.append(s5)
        print(s5)
        s7.writelines([s5])
    
    s.close()
    s7.close()

if __name__ == "__main__":
    if not len(sys.argv) <2:
        for i in sys.argv[1:]:
            if i[-4:] == '.txt':
                main(i.strip('\'\"\\').rstrip("/"))
    else:
        print("\tTo Translate a txt from Eng to Chinese,")
        print("\tUse the tool via:")
        print("\tpython *this [*txt.path]")
        